package com.fs.files.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fs.files.pojo.html.HtmlPojo;
import com.fs.files.pojo.html.TablePojo;
import com.fs.files.pojo.html.TdPojo;
import com.fs.files.pojo.html.TrPojo;
import com.fs.files.service.HtmlService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class HtmlServiceImpl implements HtmlService {
	
	@Override
	public HtmlPojo readHtml(String path) throws JsonProcessingException {
		File input = new File(path);
		//html对象
		HtmlPojo htmlPojo = new HtmlPojo();
		try {
			Document doc = Jsoup.parse(input, "UTF-8");
			//table对象集合
			List<TablePojo> tablePojoList = new ArrayList<TablePojo>();
			//遍历文档中所有的table标签
			Elements tabs = doc.select("table");
			for(int i = 0;i<tabs.size(); i++){
				//table对象
				TablePojo tablePojo = new TablePojo();
				tablePojo.setIndex(String.valueOf(i));
				tablePojoList.add(tablePojo);
				//tr对象集合
				List<TrPojo> trPojoList = new ArrayList<TrPojo>();
				//遍历当前table中的tr标签
				Elements trs = tabs.get(i).select("tr");
				for (int k = 0; k < trs.size(); k++) {
					//tr对象
					TrPojo trPojo = new TrPojo();
					trPojo.setIndex(String.valueOf(k));
					List<TdPojo> tdPojoList = new ArrayList<TdPojo>();
					//遍历当前tr的td标签
					Elements tds = trs.get(k).select("td");
					for (int j = 0; j < tds.size(); j++) {
						//获取td的内容
						String value = tds.get(j).text();
						TdPojo tdPojo = new TdPojo(String.valueOf(j), value);
						tdPojoList.add(tdPojo);
					}
					trPojo.setTds(tdPojoList);
				}
				tablePojo.setTrs(trPojoList);
			}
			htmlPojo.setTables(tablePojoList);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return htmlPojo;
	}
	
	@Override
	public String readHtmlToJsonString(String path) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		HtmlPojo htmlPojo = readHtml(path);
		String json = mapper.writeValueAsString(htmlPojo);
		return json;
	}

}
